package zhouzhouyongche.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;

import zhouzhouyongche.client_util.ErrorCode;
import zhouzhouyongche.model.Passenger;
import zhouzhouyongche.model.User;

@Repository
public class UserDao extends HibernateDao<User>{

	public List<Passenger> getPassenger(int userId) {
		String hql = "select u.passengers "
				+ "from User as u "
				+ "where u.id = ?";
		Query q = getCurrentSession().createQuery(hql);
		q.setInteger(0, userId);
		return q.list();
	}

	public int signIn(String phoneNumber, String password) {
		int userId = -1;
		String hql = "select u.id "
				+ "from User as u "
				+ "where u.phoneNumber = ? "
				+ "and u.userPassword = ?";
		Query q = getCurrentSession().createQuery(hql);
		q.setString(0, phoneNumber);
		q.setString(1, password);
		try {
			if (q.list().size() > 0)
				userId = (int)q.list().get(0);
		} catch(Exception e) {
			e.printStackTrace();
		}
		return userId;
	}

	public int signUp(String phoneNumber, String password) {
		boolean result = true;
		User user = new User();
		user.setPhoneNumber(phoneNumber);
		user.setUserPassword(password);
		
		try {
			save(user);
		} catch(Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result ? ErrorCode.SUCCESS : ErrorCode.ERROR_SIGN_UP;
	}

}
